import Enumerable from 'linq';

/*
 * 分组
 * @private
 * @param data JSON数组
 * @param group_fields 分组的字段
 */
export default function groupby<T = {}>(data: T[], group_fields: Array<keyof T>) {
	const len = group_fields.length;
	if (len === 0) {
		return data;
	} else if (len === 1) {
		const group_field = group_fields[0];
		return Enumerable.from(data).groupBy((it) => {
			return it[group_field];
		}, (it) => {
			return it;
		}, (it) => {
			return it as Partial<T>;
		}).toArray();
	} else {
		return Enumerable.from(data).groupBy((it) => {
			return JSON.stringify(group_fields.reduce((pre, cur) => {
				return {
					...pre,
					[cur]: it[cur]
				};
			}, {}));
		}, (it) => {
			return it;
		}, (it) => {
			return JSON.parse(it) as Partial<T>;
		}).toArray();
	}
}
